package itext.test.example.finalItext;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;

public class PdfPositionParse {

	private PdfReader reader;
	
	// List 中存放需要查找的文本
	private List<String> findText = new ArrayList<String>(); 
	private PdfReaderContentParser parser;

	public PdfPositionParse(String fileName) throws IOException {
		FileInputStream in = null;
		try {
			in = new FileInputStream(fileName);
			byte[] bytes = new byte[in.available()];
			in.read(bytes);
			init(bytes);
		} finally {
			in.close();
		}
	}

	public PdfPositionParse(byte[] bytes) throws IOException {
		init(bytes);
	}

	private boolean needClose = true;

	/**
	 * 传递进来的reader不会在PdfPositionParse结束时关闭
	 * 
	 * @param reader
	 */
	public PdfPositionParse(PdfReader reader) {
		this.reader = reader;
		parser = new PdfReaderContentParser(reader);
		needClose = false;
	}

	public void addFindText(String text) {
		this.findText.add(text);
	}

	private void init(byte[] bytes) throws IOException {
		reader = new PdfReader(bytes);
		parser = new PdfReaderContentParser(reader);
	}

	/**
	 * 解析指定页码处的文本，获取该文本的位置信息
	 * 
	 * @throws IOException
	 */
	public Map<String, ReplaceRegion> parse(int pageNum) throws IOException {
		
		try {
			
			//如果需要查找的文本为空，则返回运行时异常
			if (this.findText.size() == 0) {
				throw new NullPointerException("没有需要查找的文本");
			}
			//通过自定义分析器（继承接口）来解析需要查找的文本
			PositionRenderListener listener = new PositionRenderListener(this.findText);
			
			parser.processContent(pageNum, listener);
			
			//返回被查找文本信息的位置
			return listener.getResult();
		
		} finally {
			if (reader != null && needClose) {
				reader.close();
			}
		}
	}

}
